﻿using Furion.EventBus;

namespace GoodAdmin.System;

public class UserEventSubscriber:IEventSubscriber,ISingleton
{
    private readonly IRedisCacheManager _redisCacheManager;
    private readonly IServiceProvider _service;

    public UserEventSubscriber(IRedisCacheManager redisCacheManager,IServiceProvider service)
	{
        _redisCacheManager = redisCacheManager;
        _service = service;
    }

    /// <summary>
    /// 根据menu id列表移除用户数据范围
    /// 主要用于菜单修改和删除时
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    [EventSubscribe(EventSubscriberConst.RemoveDataScopeByMenuIds)]
    public async Task RemoveUserDataScopeByMenuIds(EventHandlerExecutingContext context)
    {
        //获取菜单ID
        var menuIds = (List<long>)context.Source.Payload;
        // 创建新的作用域
        using var scope = _service.CreateScope();
        // 解析关联关系服务
        var relationService = scope.ServiceProvider.GetRequiredService<IRelationService>();
        var roleIdList = (await relationService.GetRelationListByTargetId(CategoryConst.RELATION_ROLE_MENU, menuIds)).Select(it => it.ObjectId).Distinct().ToList();
        //再根据角色查询用户
        var userIdList = (await relationService.GetRelationListByTargetId(CategoryConst.RELATION_ROLE_USER, roleIdList)).Select(it => it.TargetId.ToString()).Distinct().ToList();
        //移除数据范围
        foreach (var userId in userIdList)
        {
            var key = CacheConst.DataScope + userId;
            _redisCacheManager.Remove(key);
        }
    }
}